package com.siemens.industrial.web.mvc.service.admin;

import com.siemens.industrial.model.admin.Tenant;
import com.siemens.industrial.model.admin.User;
import com.siemens.industrial.utils.GlobalResponseCode;
import com.siemens.industrial.utils.JsonToOtherFormat;
import com.siemens.industrial.utils.SiemensException;
import com.siemens.industrial.utils.UUIDGenerator;
import com.siemens.industrial.web.mvc.dao.admin.UserDao;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by qupen on 2016/8/31.
 */
@Service
public class UserService {
    @Resource
    UserDao userDao;

    @Resource
    JdbcTemplate jdbcTemplate;

    public int getUserAccount() {
        return userDao.getUserCount();
    }

    public List<User> getUserList() {
        return userDao.getUsers();
    }

    public int resetPassword(String password, String userId) {
        return userDao.initPassword(password, userId);
    }

    public User getUserByUserId(String userId) {
        List<User> users = userDao.findOneById(userId);
        if (users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    public int updateUser(Map<String, Object> o) throws SiemensException {
        if (o.containsKey("userId")) {
            User user = this.getUserByUserId(o.get("userId").toString());
            if (o.containsKey("logoMd5")) {
                user.setLogoMd5(o.get("logoMd5").toString());
            }
            if (o.containsKey("telephone")) {
                user.setTelephone(o.get("telephone").toString());
            }
            if (o.containsKey("email")) {
                user.setTelephone(o.get("email").toString());
            }
            if (o.containsKey("department")) {
                user.setDepartment(o.get("department").toString());
            }
            if (o.containsKey("userName")) {
                user.setUserName(o.get("userName").toString());
            }
            return userDao.updateUser(user);
        } else {
            throw new SiemensException(GlobalResponseCode.ERROR_STATE_EXISTED);
        }
    }

    public int enableOrDisable(String userId, int enabled) {
        return userDao.updateEnabled(userId, enabled);
    }

    public boolean getUserByUserName(String userName) {
        User user = userDao.findOneByName(userName);
        return user == null ? false : true;
    }

    public Tenant getTenantByTenantName(String tenantName) {
        Tenant tenant = userDao.findTenantByName(tenantName);
        return tenant == null ? null : tenant;
    }

    public void saveUser(Map<String, Object> o, String password, String userId) throws SiemensException {
        if (o.containsKey("userName")) {
            if (!this.getUserByUserName(o.get("userName").toString())) {
                User user = new User();
                user.setUserPwd(password);
                user.setUserId(userId);
                if (o.containsKey("logoMd5")) {
                    user.setLogoMd5(o.get("logoMd5").toString());
                }
                if (o.containsKey("role")) {
                    user.setRoleId(Integer.parseInt(o.get("role").toString()));
                }
                if (o.containsKey("telephone")) {
                    user.setTelephone(o.get("telephone").toString());
                }
                if (o.containsKey("email")) {
                    user.setEmail(o.get("email").toString());
                }
                if (o.containsKey("department")) {
                    user.setDepartment(o.get("department").toString());
                }
                user.setUserName(o.get("userName").toString());
                userDao.save(user);
            } else {
                throw new SiemensException(GlobalResponseCode.ERROR_USER_NOT_CREATE);
            }
        }
    }

    public int getMessageAccount(String userId) {
        return userDao.getMessCount(userId);
    }

    public List<Map<String, Object>> getAllMessage(String eventType, String executant, String operands, String service, String createTime) {
        String sql = "select * from  `siemens`.`message` where 1=1";
        if (!eventType.equals("")) {
            sql += " and `event_id` ='" + eventType + "'";
        }
        if (!executant.equals("")) {
            sql += " and `executant` = '" + executant + "'";
        }
        if (!operands.equals("")) {
            sql += " and `operands` ='" + operands + "'";
        }
        if (!service.equals("")) {
            sql += " and `service_id` = '" + service + "'";
        }
        if (!createTime.equals("")) {
            sql += " and date(`create_time`) =date('" + createTime + "')";
        }

        String thisSql = "select a.*,b.event_name from (" + sql + ") a inner join `siemens`.`event` b on a.event_id = b.event_id;";
        return userDao.getAllMessage(thisSql);
    }

    public void updateStatus(String userId) {
        userDao.updateStatusForMessage(userId);
    }

    //dataTable search user list
    public Map<String, Object> getUserListByDataTable(HttpServletRequest request) {
        DataTableQuery dt = new DataTableQuery(request);
        List<Map<String, Object>> list = new ArrayList<>();

        String totalSql = "SELECT COUNT(1) FROM `siemens`.`user` WHERE `enabled` <> -1";
        String sql = "Select * from `siemens`.user where `enabled`<> -1";
        int total = jdbcTemplate.queryForObject(totalSql, Integer.class);
        int filteredCount = total;
        if (!dt.getSearch().equals("")) {
            String search = " and (`user_name`like '%" + dt.getSearch() + "%' or `telephone` like '%" + dt.getSearch() + "%' or `department` like '%" + dt.getSearch() + "%' or `enabled` like '%" + dt.getSearch() + "%')";
            sql += search;
            filteredCount = jdbcTemplate.queryForObject(totalSql + search, Integer.class);
        }

        if (!dt.getOrderDBColumn().equals("") && !dt.getOrderAscOrDesc().equals("")) {
            String order = " ORDER BY `" + dt.getOrderDBColumn() + "` " + dt.getOrderAscOrDesc();
            sql += order;
        }

        String limit = " limit " + dt.getStart() + "," + dt.getLength();
        sql += limit;

        list = jdbcTemplate.queryForList(sql);
        return dt.buildResponse(filteredCount, total, list);
    }

    public List<Map<String, Object>> getMessageDistanctExecutant(String executant) {
        return userDao.findAllLikeExecutant(executant);
    }

    public List<Map<String, Object>> getMessageDistanctOperands(String operands) {
        return userDao.findAllLikeOperands(operands);
    }

    public Map<String, Object> getAllMessageByDataTable(String eventType, String executant, String operands, String service, String createTime,HttpServletRequest request) {
        DataTableQuery dt = new DataTableQuery(request);
        List<Map<String ,Object>> list = new ArrayList<>();

        String sql = "select * from  `siemens`.`message` where 1=1";
        if (!eventType.equals("")) {
            sql += " and `event_id` ='" + eventType + "'";
        }
        if (!executant.equals("")) {
            sql += " and `executant` = '" + executant + "'";
        }
        if (!operands.equals("")) {
            sql += " and `operands` ='" + operands + "'";
        }
        if (!service.equals("")) {
            sql += " and `service_id` = '" + service + "'";
        }
        if (!createTime.equals("")) {
            sql += " and date(`create_time`) =date('" + createTime + "')";
        }

        String thisSql = "select m.* from (select a.*,b.event_name from (" + sql + ") a inner join `siemens`.`event` b on a.event_id = b.event_id) m where 1=1 \n";
        int total = jdbcTemplate.queryForList("SELECT a.*, b.event_name FROM (SELECT * FROM `siemens`.`message` WHERE 1 = 1) a INNER JOIN `siemens`.`event` b ON a.event_id = b.event_id;").size();

        int filteredCount = jdbcTemplate.queryForList(thisSql).size();
//        if(!dt.getSearch().equals("")){
//            String search = " and (event_name like '%'" + dt.getSearch() + "'%' or executant like '%'" + dt.getSearch() + "'%' or operands like '%'" + dt.getSearch() + "'%' or service_id like '%'" + dt.getSearch() + "'%' or create_time like '%'" + dt.getSearch() + "'%')";
//            thisSql += search;
//            filteredCount = jdbcTemplate.queryForList(thisSql).size();
//        }
        if (!dt.getOrderDBColumn().equals("") && !dt.getOrderAscOrDesc().equals("")){
            String order = " order by `" + dt.getOrderDBColumn() + "` " + dt.getOrderAscOrDesc() + "\n";
            thisSql += order;
        }

        String limit = " limit " + dt.getStart() + "," + dt.getLength();
        thisSql += limit;

        list = jdbcTemplate.queryForList(thisSql);
        return dt.buildResponse(filteredCount,total,list);
    }
}
